package zhieasy.cn.xpu_helper.controller.common;

import cn.zouchanglin.spider_xpu.SpiderResult;
import cn.zouchanglin.spider_xpu.core.SpiderCore;
import cn.zouchanglin.spider_xpu.entity.Course;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import zhieasy.cn.common.form.StudentAuthForm;
import zhieasy.cn.common.utils.ResultVOUtil;
import zhieasy.cn.common.utils.result.ResultUtils;
import zhieasy.cn.common.vo.ResultVO;
import zhieasy.cn.common.vo.common.StudentAuthVO;
import zhieasy.cn.model.common.StudentUser;
import zhieasy.cn.model.common.WechatUser;
import zhieasy.cn.service.common.StudentUserService;

import javax.annotation.Resource;
import java.util.List;

/**
 * 学生信息认证
 * @author zouchanglin
 */
@Api(tags = "common模块，学生信息类操作接口")
@Slf4j
@RestController
@RequestMapping("/common/schoolWeb")
public class StudentAuthController {
    @Resource
    private StudentUserService studentUserService;

    /**
     * 认证之前先获得SessionCode与验证码图片
     */
    @GetMapping("/getCode")
    public ResultVO getCode(){
        // 1、获取验证码URL
        String url = SpiderCore.getCheckCodeUrl(WechatUser.getWechatUserOpenIdFromSecurityContext());
        return ResultVOUtil.success(url);
    }

    @PostMapping("/login")
    public ResultVO loginSchoolWeb(String code){
        String a = "41609050128";
        String b = "ndl04551";
        SpiderResult spiderResult = null;
        try {
            // 2、获取同步调用结果只返回用户信息 + 当前学年的课表
            spiderResult = SpiderCore.go(a, b, code, WechatUser.getWechatUserOpenIdFromSecurityContext());
        }catch (Exception e) {
            // 登录失败
            System.out.println(e.toString());
        }
        System.out.println("同步调用只返回用户信息+当前学年的课表：" + spiderResult);
        List<Course> course = spiderResult.getCourse();

        //设置一下开学的的第一周



        return ResultUtils.success(code);
    }



    @ApiOperation(value = "学生身份认证", notes = "输入学号和密码进行学生认证", httpMethod = "POST")
    @PostMapping(value = "/auth", consumes = "application/json")
    public ResultVO studentInfoAuth(@RequestBody StudentAuthForm studentAuthForm){
        String wxOpenId = WechatUser.getWechatUserOpenIdFromSecurityContext();
        StudentUser studentUser = studentUserService.authStudentInfo(studentAuthForm, wxOpenId);

        if(studentUser != null) {
            StudentAuthVO authVO = new StudentAuthVO();
            authVO.setStudentId(studentUser.getStudentId());
            authVO.setStudentCollege(studentUser.getCollegeId());
            authVO.setStudentSchool("西安工程大学");
            authVO.setStudentGrade(studentUser.getGradeId());
            authVO.setStudentName(studentUser.getStudentName());
            return ResultVOUtil.success(authVO);
        }
        return ResultVOUtil.error(1, "学生身份认证出错");
    }
}
